import FontFaceObserver from 'fontfaceobserver'
const loadFontList:any[] = []
export type Font = {
  fontName: string;
  fontFile: string;
  isDefault: string|number
};

declare global {
  interface Window {
    _graphFontList_: Font[];
  }
}

export async function loadFont(fontName: string): Promise<void> {
  const font = window._graphFontList_.find(item => item.fontName === fontName);

  if (!font) {
    throw new Error(`Font ${fontName} not found in _graphFontList_`);
  }
  const fontUrl = font.fontFile;
  if (loadFontList.includes(fontName)) {
    return;
  }
  // 创建一个style标签
  const style = document.createElement('style');
  style.type = 'text/css';
  // 定义@font-face规则
  const fontFace = `
    @font-face {
      font-family: '${fontName}';
      src: url('${fontUrl}') format('truetype');
    }
  `;
  style.appendChild(document.createTextNode(fontFace)); // 其他浏览器
  document.head.appendChild(style);
  const fontObserver = new FontFaceObserver(fontName);
  try {
    await fontObserver.load(null, 60 * 1000 * 2);
    console.log(`Font ${fontName} loaded successfully.`);
    loadFontList.push(fontName);
  } catch (err) {
    console.error(`Failed to load font: ${fontName}`, err);
    throw err;
  }
}
